<?php

namespace app\api\controller;

use app\admin\model\Banner;
use app\admin\model\Coupons;
use app\admin\model\Hall;
use app\admin\model\refund\Reason;
use app\admin\model\user\Coupons as UserCouponsModel;
use app\common\controller\Api;
use app\admin\model\Order;
use app\common\model\OrderTicket;
use think\Env;
use think\Log;
use app\admin\model\Winemenu;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * 小程序审核
     *
     */
    public function miniCheck()
    {
        $minicheck = Env::get('app.minicheck', 0);
        $result = $minicheck ? 1 : 2;
        $this->success('请求成功',$result);
    }
    /**
     * 轮播图
     *
     */
    public function banner()
    {
        $list = Banner::where(['is_show'=>1])->order('weigh','desc')->select();
        if ($list){
            foreach ($list as $key=>&$value){
                $value['image'] = compatImage($value['image']);
            }
        }
        $this->success('轮播图',$list);
    }

    /**
     * 系统配置
     *
     */
    public function sysconfig()
    {

        $data = [];
        //首页配置(基础配置)
        $data['index_name_zh'] = config('site.index_name_zh');
        $data['index_name_en'] = config('site.index_name_en');
        $data['store_address'] = config('site.store_address');
        $data['store_address_lng'] = config('site.store_address_lng');
        $data['store_address_lat'] = config('site.store_address_lat');
        $data['store_phone'] = config('site.store_phone');
        $data['index_bottom_image'] = cdnurl(config('site.index_bottom_image'),true);
        $data['index_top_image'] = cdnurl(config('site.index_top_image'),true);
        $data['seat_background_image'] = cdnurl(config('site.seat_background_image'),true);

        //文章配置
        $data['article_user_agreement'] = config('site.article_user_agreement');
        $data['article_privacy_policy'] = config('site.article_privacy_policy');
        $data['article_service_agreement'] = config('site.article_service_agreement');
        $data['article_introduce'] = config('site.article_introduce');
        $data['booking_notice'] = config('site.booking_notice');

        //妆造配置
        $data['makeup_price'] = config('site.makeup_price');
        $makeup_time_arr = explode(',',config('site.makeup_time'));
        $data['makeup_time_arr'] = $makeup_time_arr;
        $data['makeup_des'] = config('site.makeup_des');
        $data['makeup_detail'] = config('site.makeup_detail');
        $data['private_room'] = config('site.private_room');

        //酒套餐配置
        $data['wine_des'] = config('site.wine_des');
        $data['wine_price'] = config('site.wine_price');

        $this->success('系统配置',$data);
    }

    /*
     * 退票原因
     * */
    public function refundReason()
    {
        $list = Reason::order('weigh','desc')->select();
        $this->success('退票原因',$list);
    }

    /*
     * 酒套餐列表
     * */
    public function wineMenu()
    {
        $list = Winemenu::where(['status'=>1])->order('sort','asc')->select();
        $this->success('酒套餐列表',$list);
    }
    /*
     * 发放生日优惠券
     * */
    public function sendBirthdayCoupons()
    {
        $birthday_coupons = config('site.birthday_coupons');
//        Log::info('生日优惠券');
        $today_m_d = datetime(time(),'m-d');
        if ($birthday_coupons)
        {
            $birthday_coupons_arr = explode(',',$birthday_coupons);
//            var_dump($birthday_coupons_arr);

            $birthday_user = \app\admin\model\User::where(['birthday_m_d'=>$today_m_d,'status'=>'normal'])->select();
            if ($birthday_user)
            {
                foreach ($birthday_user as $key=>$value){
                    foreach ($birthday_coupons_arr as $v){
                        $coupon = Coupons::get($v);
                        if ($coupon){
                            $endtime = (($coupon['usetime']+1) * 86400)+time();
                            UserCouponsModel::create([
                                'user_id' => $value['id'],
                                'coupons_id' => $coupon['id'],
                                'endtime' => date('Y-m-d',$endtime),
                                'createtime' => time(),
                            ]);
                        }
                    }
                }
            }
        }

        $this->success('发放生日优惠券',['num'=>isset($birthday_user)?count($birthday_user):0,'birthday_coupons'=>$birthday_coupons,'m-d'=>$today_m_d]);
    }

    public function enCode(){
        die;
        $original_string = $this->request->param('content');  // Plain text/String
        $cipher_algo = "AES-128-CTR"; //The cipher method, in our case, AES
        $iv_length = openssl_cipher_iv_length($cipher_algo); //The length of the initialization vector
        $option = 0; //Bitwise disjunction of flags
        $encrypt_iv = '8746376827619797'; //Initialization vector, non-null
        $encrypt_key = "thisispassword"; // The encryption key
        // Use openssl_encrypt() encrypt the given string
        $encrypted_string = openssl_encrypt($original_string, $cipher_algo,
            $encrypt_key, $option, $encrypt_iv);
        $this->success('成功', $encrypted_string);
    }

    public function deCode(){
        die;
        $encrypted_string = $this->request->param('content');  // Plain text/String
        $cipher_algo = "AES-128-CTR"; //The cipher method, in our case, AES
        $option = 0; //Bitwise disjunction of flags
        //Decryption
        $decrypt_iv = '8746376827619797'; //Initialization vector, non-null
        $decrypt_key = "thisispassword"; // The encryption key
        // Use openssl_decrypt() to decrypt the string
        $decrypted_string=openssl_decrypt ($encrypted_string, $cipher_algo,
            $decrypt_key, $option, $decrypt_iv);
        $this->success('成功', $decrypted_string);
    }

    /*
     * 生成座位（测试用）
     * */
    public function createSeat()
    {
        // 初始化主数组
        $gridData = array();

        // 生成35行数据
        for ($rowIndex = 0; $rowIndex < 50; $rowIndex++) {
            $rowData = array();

            // 生成每行的20列数据
            for ($colIndex = 0; $colIndex < 20; $colIndex++) {
                $cell = array(
                    "XCoord" => $rowIndex,
                    "YCoord" => $colIndex,
                    "status" => 0,
                    "RowNum" => $rowIndex + 1,
                    "ColumnNum" => $colIndex + 1,
                    "Price" => 0,
                    "level" => "normal",
                    "alias" => "",
                    "select" => 0
                );
                array_push($rowData, $cell);
            }
            array_push($gridData, $rowData);
        }
        $gridData = json_encode($gridData, JSON_UNESCAPED_UNICODE);
        halt($gridData);
        $this->success('生成座位（测试用）', $gridData);
    }


    /*
     *
     * 给座位增加别名字段（测试用）
     * */
    public function generateAlias()
    {
        $hall = Hall::where(['id'=>1])->find();
        $hall_seat_data = json_decode($hall['seat_data'],true);
        foreach ($hall_seat_data as $key=>&$value)
        {
            foreach ($value as $k=>&$v)
            {
                $v['alias'] = '';
            }
        }
        $hall_seat_data = json_encode($hall_seat_data, JSON_UNESCAPED_UNICODE);
        halt($hall_seat_data);
        $this->success('给座位增加别名字段', $hall_seat_data);
    }

    /*
     * 到开席时间更新订单状态(计划任务)
     * */
    public function updateOrderStatus()
    {
        $OrderModel = new Order();
        $order = $OrderModel->where(['status'=>1])->whereTime('start_time','<=',time())->update(['status'=>2]);

        $this->success('到开席时间更新订单状态', $order);
    }

    /*
     * 取消订单(计划任务)
     * */
    public function cancelOrder()
    {
        $OrderModel = new Order();
        //获取创建时间超过三分钟且未支付的订单列表
        $order = $OrderModel->where(['status'=>0])->whereTime('createtime','<=',time()-180)->select();
        if ($order)
        {
            $OrderTicket = new OrderTicket();
            foreach ($order as $key=>$value)
            {
                $OrderModel->where(['id'=>$value['id']])->update(['status'=>-1]);
                //取消座位订单

                $order_ticket_list = $OrderTicket->where(['status'=>0,'order_id'=>$value['id']])->select();
                foreach ($order_ticket_list as $order_ticket){
                    $order_ticket->status = -1;
                    $order_ticket->save();
                }
            }
        }

    }
}
